<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd" v-if="!selectionMaterialShow && !requestDetailShow">
      <!-- 筛选按钮 -->
      <div class="search-button" v-if="!contactAddShow">
        <el-button
          v-if="pageType === 'check' && route.name === 'OrderCheck'"
          class="btn save"
          @click="handleCheckBtn2(projectFormRef, 3, '同意')"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >同意</el-button
        >
        <el-button
          v-if="pageType === 'check' && route.name === 'OrderCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 4, '拒绝')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >拒绝</el-button
        >

        <el-button
          v-if="pageType === 'check' && route.name === 'OrderCheck'"
          class="btn withdraw"
          @click="handleCheckBtn2(projectFormRef, 6, '驳回')"
          ><el-icon class="icon" color="#fff"> <DocumentDelete /> </el-icon
          >驳回</el-button
        >
        <el-button
          v-if="pageType !== 'detail' && pageType !== 'check'"
          class="btn submit"
          @click="handleAddSave(requestFormRef, 1)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >提交</el-button
        >
        <el-button
          v-if="
            pageType !== 'detail' &&
            pageType !== 'check' &&
            pageType !== 'change'
          "
          class="btn save"
          @click="handleAddSave(requestFormRef, 0)"
          ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
          >存为草稿</el-button
        >
        <el-button
        v-if="activeName == 'approval' && flowInfoList.length"
        @click="handleEvaluate()"
        class="btn save"
        ><el-icon class="icon" color="#fff"> <Comment /> </el-icon
        >评论</el-button
      >
        <el-button v-if="activeName == 'approval' && flowInfoList.length" @click="handlePrint()" v-print="prints" class="btn add"
        ><el-icon class="icon" color="#fff"> <Printer /> </el-icon
        >打印</el-button
      >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="采购订单信息" name="info">
          <el-collapse v-model="activeNames">
            <!-- 基础信息 -->
            <el-collapse-item
              name="1"
              v-if="!contactAddShow"
              class="transform-down"
            >
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title" v-if="pageType === 'edit'"
                  >编辑</span
                >
                <span class="collapse-title" v-else-if="pageType === 'change'"
                  >变更</span
                >
                <span
                  class="collapse-title"
                  v-if="route.name === 'Inquiry' && pageType === 'add'"
                  >生成订单的</span
                >
                <span class="collapse-title">基础信息</span>
              </template>
              <div class="request-info">
                <el-form
                  :model="requestForm"
                  ref="requestFormRef"
                  :rules="queryRules"
                  label-width="100px"
                  v-enterToNext
                  :disabled="
                    pageType === 'detail' ||
                    pageType === 'check' ||
                    pageType === 'change'
                  "
                >
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="采购编号：">
                        <el-input
                          disabled
                          v-model="requestForm.purchaseOrderCode"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="申请日期："
                        prop="applicantDate"
                        label-width="135"
                      >
                        <el-date-picker
                          v-model="requestForm.applicantDate"
                          format="YYYY/MM/DD"
                          class="search-input"
                          value-format="YYYY-MM-DD"
                          type="date"
                          placeholder="请选择"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="采购人："
                        prop="applicantId"
                        label-width="135"
                      >
                        <el-select
                          v-model="requestForm.applicantId"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handleUserChange"
                        >
                          <el-option
                            v-for="dict in userList"
                            :key="dict.userId"
                            :label="dict.nickName"
                            :value="dict.userId"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="申请部门：" label-width="135">
                        <el-input
                          disabled
                          v-model="requestForm.deptName"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="采购类型：" prop="purchaseOrderType">
                        <el-select
                          v-model="requestForm.purchaseOrderType"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                        >
                          <el-option
                            v-for="dict in purchaseTypeList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="是否有询比价："
                        label-width="135"
                        prop="isInquiryPrice"
                      >
                        <el-select
                          v-model="requestForm.isInquiryPrice"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                          disabled
                        >
                          <el-option
                            v-for="dict in flagList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col
                      :span="6"
                      v-if="route.name === 'Inquiry' && pageType === 'add'"
                    >
                      <el-form-item
                        label="询比价编号："
                        label-width="135"
                        prop="inquiryCode"
                      >
                        <el-input
                          disabled
                          v-model="requestForm.inquiryCode"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="备注：">
                        <el-input
                        maxlength="2000"
                          style="width: 100%"
                          v-model="requestForm.remarks"
                          type="textarea"
                          placeholder="请输入"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row v-if="pageType === 'change' || pageType === 'detail'">
                    <el-col :span="24">
                      <el-form
                        label-width="100px"
                        :disabled="pageType !== 'change'"
                      >
                        <el-form-item label="变更说明：">
                          <el-input
                            style="width: 100%"
                            v-model="requestForm.changeReason"
                            type="textarea"
                            placeholder="请输入"
                            maxlength="2000"
                          ></el-input>
                        </el-form-item>
                      </el-form>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-item>
            <!-- 询比价信息列表 -->
            <el-collapse-item
              name="2"
              style="position: relative"
              v-if="!contactAddShow && pageType !== 'change'"
            >
              <!-- class="transform-down" -->
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">关联请购单</span>
                <div
                  class="search-button button-position"
                  v-if="
                    pageType !== 'detail' &&
                    pageType !== 'check' &&
                    pageType !== 'change'
                  "
                >
                  <el-button
                    class="btn submit"
                    @click.stop="handleRequestChoose"
                    style="width: 150px"
                    ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                    >选择关联请购单</el-button
                  >
                </div>
              </template>
              <div class="contact-info">
                <!-- 表格数据 -->
                <el-table
                  :data="
                    pageType !== 'detail' &&
                    pageType !== 'check ' &&
                    pageType !== 'change '
                      ? RequestChooseList
                      : requestListSplit
                  "
                  border
                  :height="'100%'"
                  :header-cell-style="{ 'text-align': 'center' }"
                  style="margin-bottom: 20px"
                  :row-class-name="tableRowClassName"
                >
                  <!-- 操作模式 -->
                  <el-table-column
                    label="操作"
                    align="center"
                    :show-overflow-tooltip="true"
                    width="60px"
                    v-if="
                      pageType !== 'detail' &&
                      pageType !== 'check' &&
                      pageType === 'change'
                    "
                  >
                    <template #default="{ row, $index }">
                      <div class="table-operate">
                        <img
                          src="@/assets/icons/images/delete.png"
                          class="table-icon"
                          title="删除"
                          @click="handleRequestOperate('delete', row, $index)"
                        />
                      </div> </template
                  ></el-table-column>
                  <el-table-column
                    v-if="
                      pageType === 'detail' ||
                      pageType === 'check' ||
                      pageType === 'change'
                    "
                    width="60"
                    label="序号"
                    align="center"
                  >
                    <template #default="{ row, $index }">
                      {{ row.index }}.{{ row.childrenIndex }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="请购编号"
                    prop="purchaseApplyCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="物料编号"
                    prop="materialCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #default="{ row }">
                      <span>{{
                        row.materialCode ? row.materialCode : "--"
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="物料名称"
                    prop="materialName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="出厂型号"
                    prop="factoryCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="技术参数"
                    prop="technologyParameter"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="单位"
                    prop="materialUnitName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="请购数量"
                    prop="purchaseNumber"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="单价（元）"
                    prop="purchasePrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="总价（元）"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #default="{ row }">
                      {{ row.purchasePrice * row.purchaseNumber }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="到货周期"
                    prop="deliveryCycle"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="物料图片"
                    :show-overflow-tooltip="true"
                    min-width="200"
                  >
                    <template #default="{ row }">
                      <div class="image-content" v-if="row.suppFileInfoVos">
                        <!-- <template > -->
                        <el-image
                          v-for="(item, index) in row.suppFileInfoVos"
                          :key="index"
                          :preview-teleported="true"
                          style="width: 30px; height: 30px; margin-right: 5px"
                          :src="item.url"
                          :preview-src-list="showImg(item.url)"
                        >
                          <template #error>
                            <div class="image-slot">
                              <el-icon><icon-picture /></el-icon>
                            </div>
                          </template>
                        </el-image>
                        <!-- </template> -->
                      </div>
                      <span v-if="!row.suppFileInfoVos"> 暂无图片 </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="参考链接"
                    prop="referenceLink"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="供应商"
                    prop="supplierName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="生产厂商"
                    prop="manufactureName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                </el-table>
              </div>
            </el-collapse-item>
            <!-- 添加询比价信息 -->
            <el-collapse-item
              name="3"
              style="position: relative"
              v-if="contactAddShow"
              class="transform-up"
            >
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">添加询比价</span>
                <div
                  class="search-button button-position"
                  v-if="pageType !== 'detail' && pageType !== 'change'"
                >
                  <el-button class="btn save" @click.stop="handleHand"
                    ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                    >手动添加</el-button
                  >
                  <el-button class="btn submit" @click.stop="handleMaterial"
                    ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                    >选择物料</el-button
                  >
                </div>
              </template>
              <div class="request-info">
                <el-form
                  :model="contactForm"
                  ref="contactFormRef"
                  label-width="110px"
                  v-enterToNext
                  :rules="queryContactRules"
                >
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="物料编号：">
                        <el-input
                          v-model="contactForm.materialCode"
                          placeholder="自动生成"
                          clearable
                          class="search-input"
                          disabled
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="物料名称：" prop="materialName">
                        <el-input
                          :disabled="
                            contactForm.materialCode !== '' &&
                            pageType !== 'change'
                          "
                          ref="refInput"
                          v-model="contactForm.materialName"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="采购性质：" prop="factoryCode">
                        <el-select
                          v-model="contactForm.procurementNature"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handleNatureListChange"
                        >
                          <el-option
                            v-for="dict in natureList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="出厂型号：" prop="factoryCode">
                        <el-input
                          :disabled="
                            contactForm.materialCode !== '' &&
                            pageType !== 'change'
                          "
                          v-model="contactForm.factoryCode"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="0">
                    <el-col :span="6">
                      <el-form-item
                        label="技术参数："
                        prop="technologyParameter"
                      >
                        <el-input
                          :disabled="
                            contactForm.materialCode !== '' &&
                            pageType !== 'change'
                          "
                          v-model="contactForm.technologyParameter"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="单位：" prop="materialUnit">
                        <el-select
                          :disabled="
                            contactForm.materialCode !== '' &&
                            pageType !== 'change'
                          "
                          v-model="contactForm.materialUnit"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handleUnitChange"
                        >
                          <el-option
                            v-for="dict in unitList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="采购数量：" prop="purchaseNumber">
                        <el-input
                          type="Number"
                          v-model="contactForm.purchaseNumber"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="预算单价：" prop="budgetedPrice">
                        <el-input
                          type="Number"
                          v-model="contactForm.budgetedPrice"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="预算总价：">
                        <el-input
                          disabled
                          v-model="contactForm.budgeteAllPrice"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="询价单价：" prop="purchasePrice">
                        <el-input
                          type="Number"
                          v-model="contactForm.purchasePrice"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="税率：" prop="taxRate">
                        <!-- <el-input
                      type="Number"
                      v-model="contactForm.taxRate"
                      placeholder="请输入"
                      clearable
                      class="search-input"
                      @blur="handlePrice"
                    >
                      <template #append>%</template>
                    </el-input> -->
                        <el-select
                          v-model="contactForm.taxRate"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handlePrice"
                        >
                          <el-option
                            v-for="dict in taxRateList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="税额：">
                        <el-input
                          pattern="/^\d+(\.\d{1,2})?$/"
                          disabled
                          type="Number"
                          v-model="contactForm.taxAmount"
                          placeholder="单价、自动计算"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="不含税金额：">
                        <el-input
                          disabled
                          type="Number"
                          v-model="contactForm.noTaxAmount"
                          placeholder="单价、自动计算"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="总金额：">
                        <el-input
                          disabled
                          v-model="contactForm.allPrice"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="运费：" prop="freight">
                        <el-input
                          type="Number"
                          v-model="contactForm.freight"
                          placeholder="请输入"
                          clearable
                          class="search-input"
                          @blur="handlePrice"
                        >
                          <template #append>元</template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="发票类型：" prop="invoiceType">
                        <el-select
                          v-model="contactForm.invoiceType"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handleTypeChange"
                        >
                          <el-option
                            v-for="dict in typeList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <!-- </el-row>
              <el-row> -->
                    <el-col :span="6">
                      <el-form-item label="到货周期：" prop="deliveryCycle">
                        <el-input
                          v-model="contactForm.deliveryCycle"
                          placeholder="如：一周内。方便采购了解优先级，以保障供应时效"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="渠道：" prop="channel">
                        <el-select
                          v-model="contactForm.channel"
                          placeholder="请选择"
                          clearable
                          class="search-input"
                          @change="handleChannelChange"
                        >
                          <el-option
                            v-for="dict in channelList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="供应商：">
                        <el-autocomplete
                          :disabled="
                            contactForm.materialCode !== '' &&
                            pageType !== 'change'
                          "
                          popper-class="autoclass"
                          v-model="contactForm.supplierName"
                          :fetch-suggestions="querySearch"
                          placeholder="请输入"
                          @select="handleSuppliereSelect"
                          style="width: 268px"
                          clearable
                          placement="bottom-end"
                        >
                          <template #default="{ item }">
                            <!-- <div class="auto-top"> -->
                            <div class="auto-top" style="display: flex">
                              <div class="auto-item">供应商编号</div>
                              <div class="auto-item">供应商简称</div>
                              <div class="auto-item">供应商全称</div>
                              <div class="auto-item">供应商地址</div>
                            </div>
                            <div style="display: flex; width: 500px">
                              <div class="auto-item" :title="item.supplierCode">
                                {{ item.supplierCode }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.supplierAbbreviation"
                              >
                                {{ item.supplierAbbreviation }}
                              </div>
                              <div class="auto-item" :title="item.supplierName">
                                {{ item.supplierName }}
                              </div>
                              <div
                                class="auto-item"
                                :title="`${item.provinceName}${item.cityName}${item.areaName}`"
                              >
                                {{ item.provinceName }}{{ item.cityName
                                }}{{ item.areaName }}
                              </div>
                            </div>
                          </template>
                        </el-autocomplete>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="生产厂商：">
                        <el-autocomplete
                          :disabled="
                            contactForm.materialCode !== '' &&
                            pageType !== 'change'
                          "
                          popper-class="autoclass"
                          v-model="contactForm.manufactureName"
                          :fetch-suggestions="querySearch"
                          placeholder="请输入"
                          @select="handleSuppliereSelect"
                          style="width: 268px"
                          clearable
                          placement="bottom-end"
                        >
                          <template #default="{ item }">
                            <!-- <div class="auto-top"> -->
                            <div class="auto-top" style="display: flex">
                              <div class="auto-item">供应商编号</div>
                              <div class="auto-item">供应商简称</div>
                              <div class="auto-item">供应商全称</div>
                              <div class="auto-item">供应商地址</div>
                            </div>
                            <div style="display: flex; width: 500px">
                              <div class="auto-item" :title="item.supplierCode">
                                {{ item.supplierCode }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.supplierAbbreviation"
                              >
                                {{ item.supplierAbbreviation }}
                              </div>
                              <div class="auto-item" :title="item.supplierName">
                                {{ item.supplierName }}
                              </div>
                              <div
                                class="auto-item"
                                :title="`${item.provinceName}${item.cityName}${item.areaName}`"
                              >
                                {{ item.provinceName }}{{ item.cityName
                                }}{{ item.areaName }}
                              </div>
                            </div>
                          </template>
                        </el-autocomplete>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item
                        label="关联请购单："
                        prop="purchaseInqMaterialDetailLitsRespVos"
                      >
                        <el-select
                          style="width: 268px"
                          value-key="purchaseMaterialId"
                          multiple
                          v-model="
                            contactForm.purchaseInqMaterialDetailLitsRespVos
                          "
                          placeholder="请选择"
                          clearable
                          :disabled="pageType === 'change'"
                        >
                          <!-- class="search-input" -->
                          <el-option
                            v-for="dict in RequestChooseList"
                            :key="dict.purchaseMaterialId"
                            :label="
                              dict.purchaseApplyCode +
                              ' ' +
                              dict.materialCode +
                              ' ' +
                              dict.materialName
                            "
                            :value="dict"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-item>
            <!-- 物料信息列表 -->
            <el-collapse-item
              name="4"
              style="position: relative; margin-bottom: 20px"
            >
              <!-- class="transform-down" -->
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">物料信息</span>
                <div
                  v-if="
                    pageType !== 'detail' &&
                    pageType !== 'check' &&
                    pageType !== 'change' &&
                    !contactAddShow
                  "
                  class="search-button button-position"
                >
                  <el-button class="btn add" @click.stop="handleContactOperate"
                    ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                    >添加</el-button
                  >
                </div>
                <div
                  class="search-button button-position"
                  v-else
                  v-if="
                    (pageType !== 'detail' &&
                      pageType !== 'check' &&
                      pageType !== 'change') ||
                    (pageType === 'change' && contactAddShow)
                  "
                >
                  <el-button
                    class="btn add"
                    @click.stop="handleContactAdd(contactFormRef)"
                    ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
                    >添加</el-button
                  >
                  <el-button
                    class="btn direction"
                    @click.stop="handleRequestBack"
                    ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
                    >关闭</el-button
                  >
                </div>
                <div
                  class="search-button button-position"
                  v-if="pageType == 'detail' && contactAddShow"
                >
                  <el-button
                    class="btn save"
                    @click.stop="handleContactAdd(contactFormRef, 'save')"
                    ><el-icon class="icon" color="#fff"> <Tickets /> </el-icon
                    >保存</el-button
                  >
                  <el-button
                    class="btn direction"
                    @click.stop="handleRequestBack"
                    ><el-icon class="icon" color="#fff"> <ArrowUp /> </el-icon
                    >关闭</el-button
                  >
                </div>
              </template>
              <div class="contact-info">
                <!-- 表格数据 -->
                <el-table
                  row-key="batchNumber"
                  :default-expand-all="true"
                  :data="requestForm.purchaseOrderMaterialRespVos"
                  border
                  :height="'100%'"
                  :header-cell-style="{ 'text-align': 'center' }"
                  :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren',
                  }"
                  show-summary
                  sum-text="合计"
                  :summary-method="getSummaries"
                >
                  <el-table-column type="" width="1" align="center" />
                  <!-- 操作模式 -->
                  <el-table-column
                    type=""
                    label="操作"
                    align="center"
                    :show-overflow-tooltip="true"
                    :width="pageType === 'change' ? '70px' : '100px'"
                    v-if="
                      (pageType !== 'detail' && pageType !== 'check') ||
                      pageType === 'change'
                    "
                  >
                    <template #default="{ row, $index }">
                      <div class="table-operate" v-if="!row.parentId">
                        <img
                          v-if="pageType !== 'change'"
                          src="@/assets/icons/images/edit.png"
                          class="table-icon"
                          title="编辑"
                          @click="handleOperate('edit', row, $index)"
                        />
                        <el-icon
                          v-if="pageType === 'change' && row"
                          title="变更"
                          color="#007CEF"
                          class="table-icon"
                          :size="20"
                          @click="handleOperate('edit', row, $index)"
                        >
                          <!-- <EditPen /> -->
                          <img
                            src="@/assets/icons/images/alter.png"
                            style="width: 18px; height: 18px"
                          />
                        </el-icon>
                        <img
                          v-if="pageType !== 'change'"
                          src="@/assets/icons/images/delete.png"
                          class="table-icon"
                          title="删除"
                          @click="handleOperate('delete', row, $index)"
                        />
                      </div> </template
                  ></el-table-column>
                  <!-- <el-table-column
          type="index"
          label="序号"
          width="70"
          align="center"
        /> -->
                  <el-table-column
                    v-if="pageType !== 'add' && pageType !== 'edit'"
                    type="index"
                    width="60"
                    label="序号"
                    align="center"
                  >
                    <template #default="{ row, $index }">
                      <div v-if="!row.parentId">{{ indexList[$index] }}</div>
                      <div v-else>{{ null }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    min-width="160"
                    label="物料编号"
                    :show-overflow-tooltip="true"
                  >
                    <template #default="{ row, $index }">
                      <div>{{ row.materialCode }}</div>
                      <!--  v-if="row.materialCode" -->
                      <!-- <div
                        v-else
                        v-if="pageType === 'detail'"
                        class="perfect-text"
                        @click="handleOperate('edit', row, $index)"
                      >
                        完善物料
                      </div> -->
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="物料名称"
                    prop="materialName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>物料名称</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="采购性质"
                    prop="procurementNature"
                    :show-overflow-tooltip="false"
                    min-width="180"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>采购性质</span>
                    </template>
                    <template #default="{ row, $index }">
                      <el-select
                        v-model="row.procurementNature"
                        placeholder="请选择"
                        clearable
                        class="search-input"
                        @change="handleNatureListChange"
                        size="small"
                        style="height: 50px; width: 150px"
                      >
                        <el-option
                          v-for="dict in natureList"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="出厂型号"
                    prop="factoryCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>出厂型号</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="技术参数"
                    prop="technologyParameter"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>技术参数</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单位"
                    prop="materialUnitName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>单位</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="采购数量"
                    prop="purchaseNumber"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>采购数量</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="预算单价（元）"
                    prop="budgetedPrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>预算单价（元）</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="预算总价（元）"
                    prop="budgeteAllPrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>预算总价（元）</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="询价单价（元）"
                    prop="purchasePrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="税率（%）"
                    prop="taxRate"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>税率（%）</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="税额（元）"
                    prop="taxAmount"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>税额（元）</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="不含税金额（元）"
                    prop="noTaxAmount"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>不含税金额（元）</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="运费（元）"
                    prop="freight"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>运费（元）</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="总金额（元）"
                    prop="allPrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>总金额（元）</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="发票类型"
                    prop="invoiceTypeName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>发票类型</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="到货周期"
                    prop="deliveryCycle"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>到货周期</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="渠道"
                    prop="channelName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #header>
                      <span style="color: red">* </span>
                      <span>渠道</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="供应商"
                    prop="supplierName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="生产厂商"
                    prop="manufactureName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="合同编号"
                    v-if="
                      pageType === 'detail' &&
                      [1, 2, 3].includes(requestForm.orderCheckStatus)
                    "
                    prop="purchaseContractCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    v-if="
                      pageType === 'detail' &&
                      [1, 2, 3].includes(requestForm.orderCheckStatus)
                    "
                    label="已入库数量"
                    prop="inQty"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    v-if="
                      pageType === 'detail' &&
                      [1, 2, 3].includes(requestForm.orderCheckStatus)
                    "
                    label="未入库数量"
                    prop="notInQty"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                </el-table>
              </div>
            </el-collapse-item>
            <!-- 询比价信息列表 -->
            <el-collapse-item
              v-if="pageType === 'detail'"
              name="5"
              style="position: relative"
            >
              <!-- class="transform-down" -->
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">变更记录</span>
              </template>
              <div class="contact-info">
                <!-- 表格数据 -->
                <el-table
                  row-key="batchNumber"
                  :default-expand-all="true"
                  :data="changeMaterialRespVos"
                  border
                  :height="'100%'"
                  :header-cell-style="{ 'text-align': 'center' }"
                  :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren',
                  }"
                >
                  <!-- show-summary
                  sum-text="合计"
                  :summary-method="getSummaries" -->
                  <el-table-column type="" width="1" align="center" />

                  <!-- <el-table-column
                v-if="pageType !== 'add' && pageType !== 'edit'"
                type="index"
                width="60"
                label="序号"
                align="center"
              >
                <template #default="{ row, $index }">
                  <div v-if="!row.parentId">{{ indexList[$index] }}</div>
                  <div v-else>{{ null }}</div>
                </template>
              </el-table-column> -->
                  <el-table-column
                    label=""
                    prop="changeName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="行标识"
                    prop="label"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    min-width="160"
                    label="物料编号"
                    :show-overflow-tooltip="true"
                  >
                    <template #default="{ row, $index }">
                      <div>{{ row.materialCode }}</div>
                    </template>
                  </el-table-column>

                  <el-table-column
                    label="物料名称"
                    prop="materialName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="采购性质"
                    prop="procurementNatureName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />

                  <el-table-column
                    label="出厂型号"
                    prop="factoryCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="技术参数"
                    prop="technologyParameter"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="单位"
                    prop="materialUnitName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="采购数量"
                    prop="purchaseNumber"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="预算单价（元）"
                    prop="budgetedPrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="预算总价（元）"
                    prop="budgeteAllPrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <!-- <template #default="{ row }">
                  {{ row.budgetedPrice * row.purchaseNumber }}
                </template> -->
                  </el-table-column>
                  <el-table-column
                    label="询价单价（元）"
                    prop="purchasePrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="税率（%）"
                    prop="taxRate"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="税额（元）"
                    prop="taxAmount"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="不含税金额（元）"
                    prop="noTaxAmount"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />

                  <el-table-column
                    label="运费（元）"
                    prop="freight"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="总金额（元）"
                    prop="allPrice"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <!-- <template #default="{ row }">
                  {{ row.purchasePrice * row.purchaseNumber + row.freight }}
                  {{ row.allPrice }}
                </template> -->
                  </el-table-column>
                  <el-table-column
                    label="发票类型"
                    prop="invoiceTypeName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="到货周期"
                    prop="deliveryCycle"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="渠道"
                    prop="channelName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="供应商"
                    prop="supplierName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="生产厂商"
                    prop="manufactureName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="审批进度" name="approval">
       <template v-if="auditList.length">
        <div class="contact-info" id="print-iframe" >
                     <!-- 步骤栏 -->
          <div :class="!printFlag? 'steps-box' : 'steps-print-box '">
            <el-steps
              :class="flowInfoList.length>7 ? 'BigSteps' : 'SmallSteps'"
              :active="flowingStep"
              
              finish-status="success"
            >
              <el-step v-for="(item, index) in flowInfoList" :key="index">
                <template #title>
                  <span :title="item.name">
                    {{ item.name }}
                  </span>
                </template>
                <template #description>
                  <div>
                    <p class="ription">{{ item.auditDate }}</p>
                    <p class="ription">{{ item.auditEmp }}</p>
                  </div>
                </template>
              </el-step>
            </el-steps>
          </div>
            <!-- 表格数据 -->
            <el-table
              :data="auditList"
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              sum-text=""
            >
              <!-- 操作模式 -->
              <el-table-column label="流程节点" prop="name" min-width="120">
              </el-table-column>
              <el-table-column
                label="审核人"
                prop="createUserName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核时间"
                prop="createTime"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核意见"
                prop="resultName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column label="审核备注" prop="remark" min-width="120">
              </el-table-column>
            </el-table>
          </div>
          <!-- 评论 -->
          <el-table
            style="margin-top: 60px"
            :data="evaluateList"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
            sum-text=""
          >
            <!-- 操作模式 -->
            <el-table-column label="评论内容" prop="content" min-width="500">
            </el-table-column>
            <el-table-column
              label="评论人"
              prop="createUserName"
              min-width="120"
            >
            </el-table-column>
            <el-table-column label="评论时间" prop="createTime" min-width="120">
            </el-table-column>
          </el-table>
       </template>
          <div v-else>
            暂无审核
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <SelectionMaterial
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      @submitChoose="handleSelectMaterial"
    />
    <RequestDetail
      v-if="requestDetailShow"
      v-model:requestDetailShow="requestDetailShow"
      :RequestChooseList="RequestChooseList"
      @submitChoose="handleRequestDetail"
    />

    <el-dialog
      :title="title"
      v-model="auditDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="审核备注：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="auditRemark"
          placeholder=""
          type="textarea"
          maxlength="2000"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            v-if="auditResult == 3"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >同意</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 4"
            @click="saveCheck()"
            v-loading="loadingCheck"
            >拒绝</el-button
          >
          <el-button
            style="color: #fff; background-color: rgba(245, 108, 108, 1)"
            v-if="auditResult == 6"
            @click="saveCheck()"
            v-loading="loadingCheck"
          >
            驳回</el-button
          >
          <el-button style="background-color: #fff" @click="closeAudit()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
    <el-dialog
      :title="''"
      v-model="evaluateDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="评论内容：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="evaluateInfo"
          placeholder=""
          type="textarea"
          rows="5"
          maxlength="500"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            @click="saveEvaluate()"
            >保存</el-button
          >

          <el-button style="background-color: #fff" @click="closeEvaluate()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { Picture as IconPicture } from "@element-plus/icons-vue";
import { addEvaluateApi, getEvaluateListApi } from "@/api/pub.js";
import SelectionMaterial from "./selectionMaterial";
import RequestDetail from "./requestDetail";
import Upload from "@/components/Upload/index";
import { getUserListApi } from "@/api/information/customer";
import { getProjectListApi } from "@/api/sales/project";
import {
  addInquiryApi,
  editInquiryApi,
  getInquiryDetailApi,
  checkInquiryApi,
} from "@/api/purchase/inquiry";
import {
  addOrederApi,
  editOrederApi,
  getOrderDetailApi,
  checkOrderApi,
  selectAuditList,
} from "@/api/purchase/order";
import { addMaterialApi, selectMaterialList } from "@/api/information/material";
import { getDictsApi } from "@/api/dict";
import { ElMessage, ElMessageBox } from "element-plus";
import { getSupplierListApi } from "@/api/information/supplier";
import { nextTick } from "vue";
const { proxy } = getCurrentInstance();
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "requestDtlShow",
  // 更新客户新增组件显隐
  "update:requestDtlShow",
  // 刷新父组件表格数据
  "refreshList",
]);
const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
const activeName = ref('info')
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3", "4", "5"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 树表格操作
const operateTreeType = ref("");
// 新增联系人表单显隐
const contactAddShow = ref(false);
// 选择审核
const auditDialogShow = ref(false);
const loadingCheck = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 选择请购明细显隐
const requestDetailShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑使用)
const tableIndex = ref(null);
// 树表格当前索引(编辑使用)
const tableTreeIndex = ref(null);
// 采购类型列表
const typeList = ref([]);
// 渠道列表
const channelList = ref([]);
// 单位列表
const unitList = ref([]);
// 供应商列表
const suppliereList = ref([]);
// 项目列表
const projectList = ref([]);
// 请购单明细表格选中
const RequestChooseList = ref([]);
// 询比价信息、关联请购单信息显隐
const detailFlag = ref(true);
// 表格选择
const multipleSelection = ref([]);
// 关联请购单信息明细
const tableRef = ref(null);
// 询比价信息明细表格数据
const purchaseDetailTable = ref([]);
// 序号列表
const indexList = ref([]);
// 拆分后关联请购单
const requestListSplit = ref([]);
// 采购性质列表
const natureList = ref([]);
// 采购类型列表
const purchaseTypeList = ref([]);
// 变更后物料信息
const changeMaterialRespVos = ref([]);
// 默认税率列表
const taxRateList = ref([]);

let auditList = ref([]);

// 评论
const evaluateDialogShow = ref(false);
// 评论内容
const evaluateInfo = ref("");
// 评论列表
const evaluateList = ref([]);

//审核进度数据
const flowInfoList = ref([]);
//当前进度
const flowingStep = ref(0);

// 客户表单数据模板
const requestFormTemplate = {
  isInquiryPrice: 1, // 是否有询比价(0:是,1:否)
  purchaseOrderCode: "", //	采购订单编号
  purchaseOrderType: null, //	采购类型
  applicantDate: "", // 申请日期
  applicantId: null, // 申请人id
  orderCheckStatus: null, // 采购审核状态
  type: 0, // 按钮类型0：存为草稿；1；提交
  purchaseInqMaterialDetailLitsRespVos: [], // 请购单物料信息
  purchaseOrderMaterialRespVos: [], // 采购订单信息对象
  remark: "", // 备注
};
// 询比价表单数据模板
const contactFormTemplate = {
  batchNumber: null, // 批次号
  preferred: 1, // 是否首选(0:是,1:否)
  budgetedPrice: null, // 预算单价
  channel: null, // 渠道
  channelName: null, // 渠道名称
  invoiceType: null, // 发票类型erp_invoice_type(0:专票,1:普票,2:替票)
  invoiceTypeName: null, // 发票类型erp_invoice_type(0:专票,1:普票,2:替票)
  freight: null, // 运费
  inquiryPriceId: null, //	询比价的id信息
  purchaseMaterialId: null,
  deliveryCycle: "", // 到货周期
  factoryCode: "", // 出厂编号
  procurementNature: null, // 采购性质
  procurementNatureName: null, // 采购性质(中文)
  manufactureName: "", // 生产厂商名称
  manufacturerId: null, // 生产厂商(也是供应商id)
  materialCode: "", // 	物料编号
  materialName: "", // 	物料名称
  materialUnit: null, // 	物料单位
  purchaseNumber: null, // 请购数量
  purchasePrice: null, // 	请购单价
  remarks: "", // 备注
  changeReason: "", // 变更记录
  supplierId: null, // 供应商id
  supplierName: "", // 供应商名称
  technologyParameter: "", // 技术参数
  purchaseInqMaterialDetailLitsRespVos: [], // 请购单物料信息
  budgeteAllPrice: null, // 预算总价
  allPrice: null, // 总价
  taxRate: null, // 税率
  taxAmount: null, // 税额
  noTaxAmount: null, // 不含税金额
};
const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),
  // 联系人表单
  contactForm: JSON.parse(JSON.stringify(contactFormTemplate)),
  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    applicantId: [
      { required: true, message: "请选择采购人", trigger: "change" },
    ],
    purchaseOrderType: [
      { required: true, message: "请选择采购类型", trigger: "change" },
    ],
    inquiryCode: [{ required: true, message: "", trigger: "change" }],
  },
  // 联系人表单校验规则
  queryContactRules: {
    materialName: [
      { required: true, message: "请输入物料名称", trigger: "blur" },
    ],
    factoryCode: [
      { required: true, message: "请输入出厂型号", trigger: "blur" },
    ],
    technologyParameter: [
      { required: true, message: "请输入技术参数", trigger: "blur" },
    ],
    materialUnit: [
      { required: true, message: "请选择单位", trigger: "change" },
    ],
    purchaseNumber: [
      { required: true, message: "请输入采购数量", trigger: "blur" },
    ],
    budgetedPrice: [
      { required: true, message: "请输入预算单价", trigger: "blur" },
    ],
    purchasePrice: [
      { required: true, message: "请输入询价单价", trigger: "blur" },
    ],
    taxRate: [{ required: true, message: "请输入税率", trigger: "change" }],
    freight: [{ required: true, message: "请输入运费", trigger: "blur" }],
    invoiceType: [
      { required: true, message: "请选择发票类型", trigger: "change" },
    ],
    deliveryCycle: [
      { required: true, message: "请输入到货周期", trigger: "blur" },
    ],
    channel: [{ required: true, message: "请选择渠道", trigger: "change" }],
    purchaseInqMaterialDetailLitsRespVos: [
      { required: true, message: "请选择关联请购单", trigger: "change" },
    ],
  },
  // 角色列表
  contactTypeList: [],
  // 所属行业列表
  industryList: [],
  // 用户列表
  userList: [],
  flagList: [
    {
      label: "是",
      value: 0,
    },
    {
      label: "否",
      value: 1,
    },
  ],
  auditRemark: "",
  auditResult: "",
  applyId: "",
});

const {
  requestForm,
  contactForm,
  queryRules,
  queryContactRules,
  contactTypeList,
  industryList,
  userList,
  flagList,
  auditRemark,
  auditResult,
  applyId,
} = toRefs(data);

import print from "vue3-print-nb";

// 使用自定义指令
const vPrint = print;
const printFlag = ref(false);

let prints = {
  id: "print-iframe",
  popTitle: "配置页眉标题", // 打印配置页上方的标题
  extraHead: "", // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: "预览的标题", // 打印预览的标题
  previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log("正在加载预览窗口！");
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log("已经加载完预览窗口，预览打开了！");
  }, // 预览窗口打开时的callback
  // 开始打印之前的callback
  beforeOpenCallback() {
    
    console.log("开始打印之前！");
   
  },
  openCallback() {
    console.log("执行打印了！");
  }, // 调用打印时的callback
  closeCallback() {
    console.log("关闭了打印工具！");
    printFlag.value= false
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log("点击v-print绑定的按钮了！");
    
  },
  standard: "",
  extarCss: "",
};

const handlePrint = ()=>{
  printFlag.value = true
}

// 处理评论按钮点击
const handleEvaluate = () => {
  evaluateDialogShow.value = true;
};

// 保存评论
const saveEvaluate = async () => {
  if (!evaluateInfo.value) return ElMessage.info("请输入评论内容！");
  const data = {
    businessId: requestForm.value.purchaseOrderId,
    content: evaluateInfo.value,
    modelType: 4,
  };
  const result = await addEvaluateApi(data);
  if (result.code === 200) {
    ElMessage.success(result.msg);
    evaluateDialogShow.value = false;
    evaluateInfo.value = "";
    getEvaluateList()
  }
};

// 关闭评论弹窗
const closeEvaluate = () => {
  evaluateDialogShow.value = false;
  evaluateInfo.value = "";
};

// 获取评价列表
const getEvaluateList = async () => {
  const data = {
    businessId: requestForm.value.purchaseOrderId,
    modelType: 4,
  };
  const result = await getEvaluateListApi(data);
  evaluateList.value = result.data || []
};

const handleCheckBtn2 = (requestFormRef, type, title) => {
  auditRemark.value = "";
  if (type == 3) {
    auditRemark.value = "同意";
  }

  auditResult.value = type;
  (applyId.value = requestForm.value.purchaseOrderId),
    (auditDialogShow.value = true);
  loadingCheck.value = false;
};

const saveCheck = async () => {
  if (auditRemark.value === null || auditRemark.value === "") {
    ElMessage.error("审核备注不能为空");
    return;
  }

  const obj = {
    orderCheckStatus: auditResult.value,
    purchaseOrderId: applyId.value,
    auditRemark: auditRemark.value,
  };
  try {
    loadingCheck.value = true;
    const res = await checkOrderApi(obj);
    auditDialogShow.value = false;

    //loadingCheck.value =false;

    if (res.code === 200) {
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
      return;
    }
    loadingCheck.value = false;
  } catch (error) {
    loadingCheck.value = false;

    // ElMessage.error(error);
  }
};

const closeAudit = () => {
  auditRemark.value = "";
  auditResult.value = "";
  applyId.value = "";
  auditDialogShow.value = false;
};

function flattenData(data) {
  let flattenedData = [];

  function flattenChildren(children, parentId) {
    for (let child of children) {
      let flattenedChild = { ...child };
      flattenedChild.parentId = parentId;
      flattenedData.push(flattenedChild);

      if (child.children) {
        flattenChildren(child.children, child.batchNumber);
      }
    }
  }

  for (let item of data) {
    flattenedData.push({ ...item });
    if (item.children) {
      flattenChildren(item.children, item.batchNumber);
    }
  }

  return flattenedData;
}

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
const handleAddSave = async (requestFormRef, type) => {
  let flattenedData = flattenData(
    JSON.parse(JSON.stringify(purchaseDetailTable.value))
  );
  flattenedData.forEach((item) => {
    item.children = [];
  });
  if (!requestFormRef) return;
  let materialRespVos = requestForm.value.purchaseOrderMaterialRespVos;
  if (materialRespVos.length > 0) {
    let data = materialRespVos.find((i) => i.procurementNature === "");
    if (!data) {
      await requestFormRef.validate(async (valid, fields) => {
        if (valid) {
          ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            confirmButtonClass: "confirmBtnClass",
            cancelButtonClass: "cancelBtnClass",
          })
            .then(async () => {
              requestForm.value.type = type;
              let res;
              if (!requestForm.value.purchaseOrderId) {
                // 新增询比价
                res = await addOrederApi({
                  ...requestForm.value,
                  purchaseInqMaterialDetailLitsRespVos: RequestChooseList.value,
                });
              } else {
                // 编辑询比价
                res = await editOrederApi({
                  ...requestForm.value,
                  purchaseInqMaterialDetailLitsRespVos: RequestChooseList.value,
                });
              }
              if (res.code === 200) {
                emit("update:requestDtlShow", false);
                emit("refreshList", false);
                ElMessage.success(res.msg);
                requestForm.value = JSON.parse(
                  JSON.stringify(requestFormTemplate)
                );
              } else {
                ElMessage.error(res.msg);
              }
            })
            .catch(() => {});
        }
      });
    } else {
      ElMessage.warning("请补充物料信息里面的采购性质！");
    }
  } else {
    ElMessage.warning("请添加物料信息");
  }
};

/**
 * @description: 返回
 */
const handleBack = () => {
  if (props.pageType === "detail" || props.pageType === "check") {
    emit("updateFollowAddShow", false);
    emit("update:requestDtlShow", false);
    requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
  } else {
    ElMessageBox.confirm("确定返回上一级吗?以上数据未保存将会丢失!", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      confirmButtonClass: "confirmBtnClass",
      cancelButtonClass: "cancelBtnClass",
    })
      .then(async () => {
        emit("update:requestDtlShow", false);
        requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
      })
      .catch(() => {});
  }
};

/**
 * @description: 处理手动输入
 */
const handleHand = () => {
  contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
  contactFormRef.value.resetFields();
};

/**
 * @description: 处理选择物料
 */
const handleMaterial = () => {
  selectionMaterialShow.value = true;
};

/**
 * @description: 处理选择请购单
 */
const handleRequestChoose = () => {
  requestDetailShow.value = true;
};

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionMaterialShow.value = false;
    contactForm.value.materialCode = value.materialCode;
    contactForm.value.materialName = value.materialName;
    contactForm.value.factoryCode = value.factoryCode;
    contactForm.value.technologyParameter = value.technologyParameter;
    contactForm.value.materialUnit = value.materialUnit;
    contactForm.value.materialUnitName = value.materialUnitName;
    contactForm.value.supplierName = value.distributorName;
    contactForm.value.supplierId = value.supplierId;
    contactForm.value.manufacturerId = value.manufacturerId;
    contactForm.value.manufactureName = value.manufactureName;
  } else {
    ElMessage.info("请选择物料");
  }
};

/**
 * @description: 处理请购明细选择
 */
const handleRequestDetail = async (value) => {
  if (value.length) {
    requestDetailShow.value = false;
    let requestIds = [];
    value.forEach((item) => {
      RequestChooseList.value.push(item);
      requestIds.push(item.purchaseApplyId);
    });
    let params = {
      type: "request",
      dataIds: requestIds,
    };
    const res = await selectMaterialList(params);
    if (res.code == 200) {
      res.data.forEach((item) => {
        item.purchaseInqMaterialDetailLitsRespVos = [];
        RequestChooseList.value.forEach((element) => {
          if (element.purchaseApplyId == item.purchaseApplyId) {
            item.purchaseInqMaterialDetailLitsRespVos.push(element);
          }
        });
      });
    }
    requestForm.value.purchaseOrderMaterialRespVos = [...res.data];
  } else {
    ElMessage.info("请选择请购单");
  }
};

/**
 * @description: 处理供应商、生产厂家选择
 */
const handleSuppliereSelect = (value) => {};

const querySearch = (queryString, cb) => {
  const results = queryString
    ? suppliereList.value.filter(createFilter(queryString))
    : suppliereList.value;
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};

/**
 * @description: 处理审核状态相关按钮
 * @param {String} type  类型
 * @param {String} title 标题
 */
const handleCheckBtn = (contractFormRef, type, title) => {
  ElMessageBox.confirm(`确定${title}以上数据吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "confirmBtnClass",
    cancelButtonClass: "cancelBtnClass",
  })
    .then(async () => {
      const obj = {
        orderCheckStatus: type,
        purchaseOrderId: requestForm.value.purchaseOrderId,
      };
      const res = await checkOrderApi(obj);
      if (res.code === 200) {
        emit("update:requestDtlShow", false);
        emit("refreshList", false);
        ElMessage.success(res.msg);
        contractForm.value = JSON.parse(JSON.stringify(contractFormTemplate));
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch(() => {});
};

/**
 * @description: 处理询比价明细选择
 * @param {Number} type 类型
 */
const handleDetailChoose = (type) => {
  detailFlag.value = !detailFlag.value;
};

/**
 * @description: 处理项目选择
 * @param {Number} value 选择值
 */
const handleProjectChange = (value) => {
  if (value) {
    const selectedProject = projectList.value.find(
      (item) => item.projectId === value
    );
    if (selectedProject) {
      requestForm.value.projectStatus = selectedProject.projectStatus;
      requestForm.value.projectStatusName = selectedProject.projectStatusName;
    }
  } else {
    requestForm.value.projectStatus = null;
    requestForm.value.projectStatusName = "";
  }
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理单位选择
 * @param {Number} value 选择值
 */
const handleUnitChange = (value) => {
  contactForm.value.materialUnitName =
    unitList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理采购性质选择
 * @param {Number} value 选择值
 */
const handleNatureListChange = (value) => {
  contactForm.value.procurementNatureName =
    natureList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理渠道选择
 * @param {Number} value 选择值
 */
const handleChannelChange = (value) => {
  contactForm.value.channelName =
    channelList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 处理发票类型选择
 * @param {Number} value 选择值
 */
const handleTypeChange = (value) => {
  contactForm.value.invoiceTypeName =
    typeList.value.find((item) => item.value === value)?.label || "";
};

/**
 * @description: 表格选择禁用
 * @param row：当前行数据
 * @param index：当前第几位
 */
const checkSelect = (row, index) => {
  let isChecked = true;
  if (row.checked) {
    // 判断里面是否存在某个参数
    isChecked = false;
  } else {
    isChecked = true;
  }
  return isChecked;
};

/**
 * @description: 预览照片
 * @param {String} img 图片地址
 */
const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

/**
 * @description: 计算总价
 * @param {Number} value 选择值
 */
const handlePrice = () => {
  // 预算： 单价*数量
  if (contactForm.value.budgetedPrice && contactForm.value.purchaseNumber) {
    contactForm.value.budgeteAllPrice = (
      contactForm.value.budgetedPrice * contactForm.value.purchaseNumber
    ).toFixed(2);
  }
  // 总金额： 单价*数量+运费
  if (contactForm.value.purchasePrice && contactForm.value.purchaseNumber) {
    let freight = contactForm.value.freight
      ? Number(contactForm.value.freight)
      : 0;
    contactForm.value.allPrice = (
      contactForm.value.purchasePrice * contactForm.value.purchaseNumber +
      freight
    ).toFixed(2);
  }
  // 税额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxRate) {
    contactForm.value.taxAmount = (
      (contactForm.value.purchasePrice /
        (1 + contactForm.value.taxRate * 0.01)) *
      contactForm.value.taxRate *
      0.01
    ).toFixed(2);
  }

  // 不含税金额： 单价 / (1+税率) * 税率
  if (contactForm.value.purchasePrice && contactForm.value.taxAmount) {
    contactForm.value.noTaxAmount = (
      contactForm.value.purchasePrice - contactForm.value.taxAmount
    ).toFixed(2);
  }
};

/**
 * @description: 新增、编辑联系人
 * @param {Object} contactFormRef 联系人表单引用
 */
const handleContactAdd = async (contactFormRef, flag = "") => {
  if (!contactFormRef) return;
  await contactFormRef.validate(async (valid) => {
    if (valid) {
      if (operateType.value === "edit") {
        requestForm.value.purchaseOrderMaterialRespVos[tableIndex.value] =
          JSON.parse(JSON.stringify(contactForm.value));
        if (flag == "save") {
          const res = await addMaterialApi({
            ...contactForm.value,
            perfect: 1,
          });
          if (res.code === 200) {
            contactAddShow.value = false;
            ElMessage.success(res.msg);
          } else {
            ElMessage.error(res.msg);
          }
        }
      } else {
        requestForm.value.purchaseOrderMaterialRespVos.push(
          JSON.parse(JSON.stringify(contactForm.value))
        );
      }
      contactForm.value = JSON.parse(JSON.stringify(contactFormTemplate));
      contactFormRef.resetFields();
      nextTick(() => {
        refInput.value.focus();
      });
    } else {
      console.log("error submit!");
    }
  });
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  contactForm.value.suppFileInfoVos.push({ ...response, businessType: 6 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  contactForm.value.suppFileInfoVos.splice(index, 1);
}

/**
 * @description: 处理联系人操作
 */
const handleContactOperate = () => {
  if (RequestChooseList.value && RequestChooseList.value.length) {
    const hasTrueElement = RequestChooseList.value.some(
      (item) => !item.checked
    );
    if (!hasTrueElement) {
      return ElMessage.info("表格中请购单已被关联，请选择请购单");
    }
    contactAddShow.value = true;
    operateTreeType.value = "add";
    nextTick(() => {
      refInput.value.focus();
    });
  } else {
    ElMessage.info("请选择关联请购单");
  }
};
/**
 * @description: 指定行颜色
 */
const tableRowClassName = ({ row, rowIndex }) => {
  if (row.checked == true) {
    return "warm-row";
  }
};

/**
 * @description: 关闭
 */
const handleRequestBack = () => {
  // 关联请购单选中处理
  RequestChooseList.value.forEach((item) => {
    requestForm.value.purchaseOrderMaterialRespVos.forEach((purItem) => {
      if (purItem.purchaseInqMaterialDetailLitsRespVos) {
        purItem.purchaseInqMaterialDetailLitsRespVos.forEach((value) => {
          if (item.purchaseMaterialId == value.purchaseMaterialId) {
            item.checked = true;
          }
        });
      }
    });
  });
  contactAddShow.value = false;
  // nextTick(() => {
  //   refSelect.value.focus();
  // });
};

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 1) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (
      column.property === "purchaseNumber" ||
      column.property === "budgetedPrice" ||
      column.property === "purchasePrice" ||
      // column.property === "taxRate" ||
      column.property === "taxAmount" ||
      column.property === "freight" ||
      column.property === "noTaxAmount" ||
      column.property === "allPrice" ||
      column.property === "budgeteAllPrice"
    ) {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        if( column.property !=='purchaseNumber') {
          sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
        }
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });
  if (props.pageType === "add" || props.pageType === "edit") {
    // sums[16] = sums[11] * sums[8] + sums[15];
    // sums[10] = sums[9] * sums[8];
    // sums[15] = null;
    // 14总价 9单价 6数量
    // sums[15] = sums[10] * sums[7] + sums[14];
    // sums[9] = sums[8] * sums[7];
    // sums[14] = null;
  } else {
    // sums[16] = sums[11] * sums[8] + sums[15];
    // sums[10] = sums[9] * sums[8];
    // sums[15] = null;
    // 14总价 9单价 6数量
    // sums[15] = sums[10] * sums[7] + sums[14];
    // sums[9] = sums[8] * sums[7];
    // sums[14] = null;
  }
  return sums;
};

/**
 * @description: 处理询比价信息明细树表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleTreeOperate = (type, row, tabIndex) => {
  switch (type) {
    case "edit":
      // 删除同时清除关联请购单勾选状态
      let treeData = {};
      RequestChooseList.value.forEach((item) => {
        purchaseDetailTable.value.forEach((purItem, index) => {
          if (purItem.batchNumber === row.batchNumber) {
            tableTreeIndex.value = index;
            treeData = row;
          }
        });
      });

      let newData = [];
      if (treeData.children) {
        treeData.children.forEach((chiItem) => {
          chiItem.parentId = "";
          newData.push(chiItem);
        });
      }
      newData.unshift(treeData);
      newData[0].children = [];
      addInteriorTableData.value = newData;

      // 选中关联请购单勾选状态
      RequestChooseList.value.forEach((item) => {
        newData[0].purchaseInqMaterialDetailLitsRespVos.forEach((value) => {
          if (item.purchaseMaterialId == value.purchaseMaterialId) {
            item.checked = false;
          }
        });
      });
      contactAddShow.value = true;
      setTimeout(() => {
        // 回显关联请购单选中状态
        RequestChooseList.value.forEach((item, index) => {
          newData[0].purchaseInqMaterialDetailLitsRespVos.forEach((newItem) => {
            if (item.purchaseMaterialId == newItem.purchaseMaterialId) {
              tableRef.value.toggleRowSelection(item);
            }
          });
        });
      }, 500);
      operateTreeType.value = "edit";
      break;
    case "delete":
      // 删除同时清除关联请购单勾选状态
      RequestChooseList.value.forEach((item) => {
        purchaseDetailTable.value.forEach((purItem, index) => {
          if (purItem.batchNumber === row.batchNumber) {
            purItem.purchaseInqMaterialDetailLitsRespVos.forEach((value) => {
              if (item.purchaseMaterialId == value.purchaseMaterialId) {
                item.checked = false;
              }
            });
            // 延时删除等待循环
            setTimeout(() => {
              purchaseDetailTable.value.splice(index, 1);
            }, 100);
          }
        });
      });

      break;
    default:
      break;
  }
};
/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  if (type === "edit") {
    tableIndex.value = tabIndex;
    contactForm.value = {
      ...JSON.parse(JSON.stringify(row)),
      suppFileInfoVos: JSON.parse(JSON.stringify(row)).suppFileInfoVos
        ? JSON.parse(JSON.stringify(row)).suppFileInfoVos
        : [],
    };
    contactForm.value.allPrice =
      (contactForm.value.purchasePrice * contactForm.value.purchaseNumber).toFixed(2);
    contactAddShow.value = true;
    operateType.value = "edit";
    nextTick(() => {
      refInput.value.focus(); // 聚焦
    });
  } else {
    // 删除同时清除关联请购单勾选状态
    RequestChooseList.value.forEach((item) => {
      requestForm.value.purchaseOrderMaterialRespVos.forEach(
        (purItem, index) => {
          if (purItem.batchNumber === row.batchNumber) {
            purItem.purchaseInqMaterialDetailLitsRespVos.forEach((value) => {
              if (item.purchaseMaterialId == value.purchaseMaterialId) {
                item.checked = false;
              }
            });
            // 延时删除等待循环
            setTimeout(() => {
              requestForm.value.purchaseOrderMaterialRespVos.splice(
                tabIndex,
                1
              );
            }, 100);
          }
        }
      );
    });
  }
};

/**
 * @description: 处理表格选中
 */
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

/**
 * @description: 处理关联请购单表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleRequestOperate = (type, row, tabIndex) => {
  if (row.checked) {
    return ElMessage.info("该请购单已关联，请先解除关联");
  }
  RequestChooseList.value.splice(tabIndex, 1);
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const handleDetailInfo = async (id, type) => {
  try {
    detailInfoShow.value = true;
    if (!type) {
      const res = await getOrderDetailApi(id);
      if (res) {
        requestForm.value = {
          ...res.purchaseOrderInfoRespVo,
        };
        getEvaluateList()
        // 关联请购
        // 关联请购
        // RequestChooseList.value = JSON.parse(
        //   JSON.stringify(res.purchaseInqMaterialDetailLitsRespVos)
        // );
        // requestListSplit.value = JSON.parse(
        //   JSON.stringify(res.purchaseInqMaterialDetailLitsRespVos)
        // );
        // 询比价列表
        requestForm.value.purchaseOrderMaterialRespVos =
          res.purchaseOrderMaterialRespVos;
        // 变更记录
        requestForm.value.purchaseOrderChangeMaterialRespVos =
          res.purchaseOrderChangeMaterialRespVos;

        if (requestForm.value.purchaseOrderChangeMaterialRespVos) {
          requestForm.value.purchaseOrderChangeMaterialRespVos.forEach(
            (item) => {
              item.allPrice =
                (item.purchasePrice * item.purchaseNumber +
                (item.freight ? item.freight : 0)).toFixed(2);
              item.budgeteAllPrice = (item.budgetedPrice * item.purchaseNumber).toFixed(2);
            }
          );
        }
        let data1 = res.purchaseOrderChangeMaterialRespVos;
        let data2 = res.purchaseOrderMaterialRespVos;
        changeMaterialRespVos.value = [];
        if(data1) {
          data1.forEach((item,index) => {
            item.changeName="变更后";
            item.label=index+1;
            changeMaterialRespVos.value.push(item);
            changeMaterialRespVos.value.push({
              label:item.label,
              changeName:'变更前',
              budgetedPrice: item.oldBudgetedPrice,
              channel: item.oldChannel,
              channelName: item.oldChannelName,
              deliveryCycle: item.oldDeliveryCycle,
              distributorName: item.oldDistributorName,
              factoryCode: item.oldFactoryCode,
              freight: item.oldFreight,
              invoiceType: item.oldInvoiceType,
              invoiceTypeName: item.oldInvoiceTypeName,
              manufactureName: item.oldManufactureName,
              manufacturer: item.oldManufacturer,
              manufacturerId: item.oldManufacturerId,
              materialCode: item.oldMaterialCode,
              materialName: item.oldMaterialName,
              materialUnit: item.oldMaterialUnit,
              materialUnitName: item.oldMaterialUnitName,
              noTaxAmount: item.oldNoTaxAmount,
              procurementNature: item.oldProcurementNature,
              procurementNatureName: item.oldProcurementNatureName,
              purchaseNumber: item.oldPurchaseNumber,
              purchasePrice: item.oldPurchasePrice,
              remarks: item.oldRemarks,
              supplierId: item.oldSupplierId,
              supplierName: item.oldSupplierName,
              taxAmount: item.oldTaxAmount,
              taxRate: item.oldTaxRate,
              technologyParameter: item.oldTechnologyParameter,
              allPrice:(item.oldPurchasePrice * item.oldPurchaseNumber +(item.oldFreight ? item.oldFreight : 0)).toFixed(2)
            });
          });
        }
        // // 处理关联请购单勾选
        requestForm.value.purchaseOrderMaterialRespVos.map((item, index) =>
          getIndex(item, index)
        );
        requestForm.value.purchaseOrderMaterialRespVos.forEach((item) => {
          item.oldOrderMaterialId = item.orderMaterialId;
          item.allPrice =
            (item.purchasePrice * item.purchaseNumber +
            (item.freight ? item.freight : 0)).toFixed(2);
          item.budgeteAllPrice = (item.budgetedPrice * item.purchaseNumber).toFixed(2);
          item.purchaseInqMaterialDetailLitsRespVos.forEach((chiItem) => {
            RequestChooseList.value.forEach((reqItem) => {
              if (chiItem.purchaseMaterialId == reqItem.purchaseMaterialId) {
                reqItem.checked = true;
              }
            });
          });
        });

        // // 查看详情关联请购单排序 例：1、1
        requestForm.value.purchaseOrderMaterialRespVos.forEach(
          (item, itemIndex) => {
            item.purchaseInqMaterialDetailLitsRespVos.forEach(
              (chiItem, chiItemIndex) => {
                requestListSplit.value.push({
                  ...chiItem,
                  index: itemIndex + 1,
                  childrenIndex: chiItemIndex + 1,
                });
              }
            );
          }
        );

        detailInfoShow.value = false;
      }
    } else {
      const res = await getInquiryDetailApi(id);
      requestForm.value = {
        ...res.purchaseInquiryInfoRespVo,
      };
      requestForm.value.isInquiryPrice = 0;
      // 关联请购
      RequestChooseList.value = res.purchaseInqMaterialDetailLitsRespVos;
      // 询比价列表
      requestForm.value.purchaseOrderMaterialRespVos =
        res.inqMaterialDetailLitsRespVos;
      // 变更记录
      requestForm.value.purchaseOrderChangeMaterialRespVos =
        res.purchaseOrderChangeMaterialRespVos;

      if (requestForm.value.purchaseOrderChangeMaterialRespVos) {
        requestForm.value.purchaseOrderChangeMaterialRespVos.forEach((item) => {
          item.allPrice =
            (item.purchasePrice * item.purchaseNumber +
            (item.freight ? item.freight : 0)).toFixed(2);
          item.budgeteAllPrice = (item.budgetedPrice * item.purchaseNumber).toFixed(2);
        });
      }
      // // 处理关联请购单勾选
      requestForm.value.purchaseOrderMaterialRespVos.map((item, index) =>
        getIndex(item, index)
      );
      requestForm.value.purchaseOrderMaterialRespVos.forEach((item) => {
        item.oldOrderMaterialId = item.orderMaterialId;
        item.allPrice =
          (item.purchasePrice * item.purchaseNumber +
          (item.freight ? item.freight : 0)).toFixed(2);
        item.budgeteAllPrice = (item.budgetedPrice * item.purchaseNumber).toFixed(2);
        item.purchaseInqMaterialDetailLitsRespVos.forEach((chiItem) => {
          RequestChooseList.value.forEach((reqItem) => {
            if (chiItem.purchaseMaterialId == reqItem.purchaseMaterialId) {
              reqItem.checked = true;
            }
          });
        });
      });
    }
  } catch (error) {
    detailInfoShow.value = false;
  }
  const resAudit = await selectAuditList(id);
  auditList.value = resAudit.data;
  if(resAudit.data.length){
    flowInfoList.value = resAudit.data[0].chartVo.flowList;
    flowingStep.value = resAudit.data[0].chartVo.flowingStep;
  }
};

const getIndex = (data, index) => {
  indexList.value.push(index + 1);
  if (data.children) {
    data.children.map((item, index) => getIndex(item, index));
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 类型列表
  await getDictsApi("erp_invoice_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });

  // 采购类型
  await getDictsApi("purchase_order_type").then((res) => {
    if (res.code === 200) {
      purchaseTypeList.value = res.data;
    }
  });

  // 渠道列表
  await getDictsApi("erp_channel").then((res) => {
    if (res.code === 200) {
      channelList.value = res.data;
    }
  });

  // 单位列表
  await getDictsApi("material_unit").then((res) => {
    if (res.code === 200) {
      unitList.value = res.data;
    }
  });

  // 采购性质
  await getDictsApi("erp_purchase_nature").then((res) => {
    if (res.code === 200) {
      natureList.value = res.data;
    }
  });

  // 供应商列表
  await getSupplierListApi().then((res) => {
    if (res.code === 200) {
      res.rows.forEach((item) => {
        item.value = item.supplierName;
      });
      suppliereList.value = res.rows;
    }
  });

  // 项目列表
  await getProjectListApi({}, {}).then((res) => {
    if (res.code === 200) {
      projectList.value = res.rows;
    }
  });

  await getUserListApi({}).then((res) => {
    // if (res.code === 200) {
    //   userList.value = res.rows;
    // }
    if (res.length > 0) {
      userList.value = res;
    }
  });
  // 税率列表
  await getDictsApi("default_tax_rate").then((res) => {
    if (res.code === 200) {
      taxRateList.value = res.data;
    }
  });

  // // 销售部门列表
  // await getDeptListApi().then((res) => {
  //   if (res.code === 200) {
  //     deptList.value = res.data;
  //     nextTick(() => {
  //       refSelect.value.focus(); // 聚焦
  //     });
  //   }
  // });
}

/**
 * @description: 处理请购明细选择
 * @param {Number} id
 */
const handleRequestDetailChoose = (val) => {
  RequestChooseList.value = val;
};

onMounted(() => {
  getDicts();
  if (props.pageType === "add") {
    nextTick(() => {
      refSelect.value && refSelect.value.focus();
    });
  }
});

defineExpose({
  handleDetailInfo,
  handleRequestDetailChoose,
});
</script>

<style lang="scss">
.warm-row {
  background-color: #f0f0f0 !important;
}
</style>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  .search-input {
    width: 268px;
    height: 34px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
    height: 30px;
  }
  .collapse-title {
    font-weight: bold;
    font-size: 16px;
    color: #303133 !important;
    display: flex;
  }
  .collapse-title-item {
    height: 100%;
    margin-right: 20px;
    &:hover {
      color: #007cef !important;
    }
  }
  .collapse-title-active {
    color: #007cef !important;
  }
  .perfect-text {
    color: #f59a23;
    cursor: pointer;
  }

  .ription {
      color: #8f8f8f;
      line-height: 16px;
      font-size: 12px;
    }
    :deep(.el-step__head.is-success) {
      color: #3399ff;
      border-color: #3399ff;
      position: relative;
    }
    :deep(.el-step__title) {
      font-size: 16px;
      line-height: 38px;
      position: absolute;
      top: -38px;
      width: 140px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.el-step__title.is-success) {
      color: #3399ff;
    }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: left;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
.el-table {
  border: var(--el-table-border);
}
</style>
